package com.atguigu.yygh.user.controller;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.ConstantPropertiesUtil;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/user/wx")
public class WeiXinApiController {

    @Autowired
    private UserInfoService userInfoService;


    @GetMapping("/getLoginParam")
    @ResponseBody
    public Result getLoginParam() {
        try {
            Map<String, Object> map = new HashMap<>();
            //appid *
            map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);

            //scope 网页端都是snsapi_login *
            map.put("scope", "snsapi_login");

            //url编码 *
            String redirect_uri = URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "utf-8");
            map.put("redirect_uri", redirect_uri);
            //System.out.println("redirect_uri = " + redirect_uri);

            map.put("state", System.currentTimeMillis() + "");

            return Result.ok().data(map);
        } catch (Exception e) {
            e.printStackTrace();
            throw new YyghException(20001, "数据错误");
        }
    }

    //回调方法，获取扫码人微信信息
    @GetMapping("callback")
    public String callback(String code, String state) {
        //得到临时票据code
        //System.out.println("code = " + code);
        //System.out.println("state = " + state);

        //拿code和其他值请求微信固定接口，返回 openid  accessToken
        try {
            StringBuffer buffer = new StringBuffer()
                    .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                    .append("?appid=%s")
                    .append("&secret=%s")
                    .append("&code=%s")
                    .append("&grant_type=authorization_code");
            //设置参数 format字符串拼接
            String url = String.format(buffer.toString(), ConstantPropertiesUtil.WX_OPEN_APP_ID,
                    ConstantPropertiesUtil.WX_OPEN_APP_SECRET, code);

            String result = HttpClientUtils.get(url);
            //System.out.println("result = " + result);

            JSONObject jsonObject = JSONObject.parseObject(result);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");


            //拿着access_token openid请求微信固定地址，得到扫码人信息
            StringBuffer userUrl = new StringBuffer()
                    .append("https://api.weixin.qq.com/sns/userinfo")
                    .append("?access_token=%s")
                    .append("&openid=%s");
            //向%s设置参数
            String userInfoWxUrl = String.format(userUrl.toString(),
                    access_token,
                    openid);
            String resultUserInfo = HttpClientUtils.get(userInfoWxUrl);
            JSONObject jsonObjectUserInfo = JSONObject.parseObject(resultUserInfo);
            //System.out.println("resultUserInfo = " + resultUserInfo);
            String nickname = jsonObjectUserInfo.getString("nickname");

            //把扫码人信息添加到数据库 根据openid查询表中是否存在相同信息
            UserInfo userInfo = this.selectUserByOpenid(openid);
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setOpenid(openid);
                userInfo.setNickName(nickname);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }

            Map<String, String> map = new HashMap<>();
            //绑定手机号
            String phone = userInfo.getPhone();
            if(StringUtils.isEmpty(phone)){
                map.put("openid",openid);
            } else {
                map.put("openid","");
            }

            //使用jwt生成token字符串
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);

            //跳转页面

            return "redirect:http://localhost:3000/weixin/callback" +
                    "?token="+map.get("token")+
                    "&openid="+map.get("openid")+
                    "&name="+URLEncoder.encode(map.get("name"),"utf-8");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public UserInfo selectUserByOpenid(String openid) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid", openid);
        UserInfo userInfo = userInfoService.getOne(wrapper);
        return userInfo;
    }
}
